package com.zfh.rr;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


@WebServlet("/file")
@MultipartConfig(location = "d:/tmp/",maxFileSize = 1024*1024*10)
public class FileServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		Part part = request.getPart("filename");
		
		// 获得文件名
		String filename = getFileName(part);
		part.write(filename);
		
		// 反馈页面信息
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head><title>Servlet接收文件反馈结果</title></head>");
		out.println("<body>");
		out.println("<script>alert('上传成功')</script>");
		out.println("</body>");
		out.println("</html>");
	}

	private String getFileName(Part part) {
		if(part==null) {
			return null;
		}
		String fileName = part.getHeader("content-disposition");
		System.out.println(fileName);
		if(fileName=="" || fileName==null) {
			return null;
		}
		String realName = fileName.substring(fileName.lastIndexOf('=')+2,fileName.lastIndexOf("\""));
		System.out.println(realName);
		return realName;
	}

}
